package com.jm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.reggie.common.CustomException;
import com.jm.reggie.dto.SetmealDto;
import com.jm.reggie.entity.Setmeal;
import com.jm.reggie.entity.SetmealDish;
import com.jm.reggie.mapper.SetmealMapper;
import com.jm.reggie.service.SetmealDishService;
import com.jm.reggie.service.SetmealService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Resource
    private SetmealDishService setmealDishService;

    //新增套餐,同时需要保存套餐和菜品的关联关系
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        //补全套餐菜品关系
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishList);
    }

    //删除套餐，同时需要删除套餐和菜品的关联数据
    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        //判断批量删除的套餐，是否为售卖状态
        LambdaQueryWrapper<Setmeal> wrapper=new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        int count = this.count(wrapper);
        if(count>0){
            //若是，则抛异常
            throw new CustomException("存在售卖套餐，无法删除");
        }
        //删除套餐表中的数据
        this.removeByIds(ids);
        //删除套餐菜品关系表中的数据
        LambdaUpdateWrapper<SetmealDish> wrapper2=new LambdaUpdateWrapper<>();
        wrapper2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(wrapper2);
    }
}
